package com.jianbing.queue;

import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.jianbing.util.PropertiesUtils;

import java.util.Properties;

/**
 * Created by Han, Tixiang on 2016/9/8 0008.
 */
public class AliyunMQProducer {
    private static Producer producer;

    public static Producer getProducer() {
        if (producer == null) {
            synchronized (AliyunMQProducer.class) {
                if (producer == null) {
                    Properties properties = new Properties();
                    properties.put(PropertyKeyConst.ProducerId, PropertiesUtils.getProperties(PropertyKeyConst.ProducerId));
                    properties.put(PropertyKeyConst.AccessKey, PropertiesUtils.getProperties(PropertyKeyConst.AccessKey));
                    properties.put(PropertyKeyConst.SecretKey, PropertiesUtils.getProperties(PropertyKeyConst.SecretKey));
                    properties.put(PropertyKeyConst.ONSAddr, PropertiesUtils.getProperties(PropertyKeyConst.ONSAddr));
                    properties.put(PropertyKeyConst.MaxReconsumeTimes,5);

                    producer = ONSFactory.createProducer(properties);
                    //在发送消息前，必须调用start方法来启动Producer，只需调用一次即可。
                    producer.start();
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            producer.shutdown();
                        }
                    });
                    return producer;
                }
            }
        }
        return producer;
    }


}
